﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;

namespace Factory
{
    public class FactoryDAO
    {

        public FactoryE obterDadosFactory()
        {
            try
            {
                DAOBase m_cnn = new DAOBase();

                #region Query
                string query =
                    @"SELECT ID
                      ,Nome
                      ,ValorInicial
                      ,ValorAtual
                  FROM Factory";
                #endregion

                SqlCommand cmd = new SqlCommand(query, m_cnn.CreateConnection());
                SqlDataReader dr = cmd.ExecuteReader();

                IList<FactoryE> factory = ReaderToObjects(dr);

                return factory.FirstOrDefault();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return null;
            }
        }

        public static IList<FactoryE> ReaderToObjects(IDataReader reader)
        {
            if (reader.IsClosed)
            {
                throw new ArgumentException("O DataReader fornecido já estava fechado.");
            }

            int ID_pos = reader.GetOrdinal("ID");
            int Nome_pos = reader.GetOrdinal("Nome");
            int ValorInicial_pos = reader.GetOrdinal("ValorInicial");
            int ValorAtual_pos = reader.GetOrdinal("ValorAtual");

            IList<FactoryE> result = new List<FactoryE>();   

            while (reader.Read())
            {
                FactoryE c = new FactoryE()
                {
                    id = reader.GetInt32(ID_pos),
                    nome = reader.GetString(Nome_pos),
                    valorAtual = reader.GetDouble(ValorAtual_pos),
                    valorInicial = reader.GetDouble(ValorInicial_pos),
                };

                result.Add(c);
            }
            return result;
        }

        public int AtualizarDados(double total)
        {
            int resultado = 0;

            try
            {
                DAOBase m_cnn = new DAOBase();

                #region query
                string query = @"update factory set valorAtual = @total";

                #endregion

                SqlCommand cmd = new SqlCommand(query, m_cnn.CreateConnection());

                //Parametros de Usuario
                cmd.Parameters.Add(new SqlParameter("total", total));  

                resultado = cmd.ExecuteNonQuery();

                m_cnn.DestroyConnection();

            }

            catch (Exception ex)
            {
               
            }

            return resultado;
        }
    }
}
